
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyProxyTest {
    public interface IHello {
        void sayHello();
    }

    static class Hello implements IHello {

        @Override
        public void sayHello() {
            System.out.println("Hello wold");
        }
    }

    static class HellWoldInvocationHandler implements InvocationHandler {

        private Object target;

        public HellWoldInvocationHandler(Object target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("------插入前置通知代码-------------");
            Object rs = method.invoke(target, args);
            System.out.println("------插后置通知代码-------------");
            return rs;
        }
    }

    public static void main(String[] args) throws Exception {
        //保持生产实现目标接口的代理类
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

        IHello hello = (IHello) Proxy.newProxyInstance(IHello.class.getClassLoader(), new Class[]{IHello.class}, new HellWoldInvocationHandler(new Hello()));

        hello.sayHello();
    }
}
